#!/usr/bin/bash
# Given a disk image and a coreos-assembler build, use supermin
# to update the disk image to the target OSTree commit "offline".
# Concretely for example if used on a pristine disk image, Ignition
# will not have run.
#
# Example usage to upgrade *from* RHCOS 4.6 to a just-built 4.8 OSTree tree,
# then do a kola basic run on it.
#
# cd /path/to/rhcos-4.8
# cp --reflink=auto /path/to/rhcos-4.6.0-x86_64-qemu.qcow2 tmp/
# cosa offline-update tmp/rhcos-4.6.0-x86_64-qemu.qcow2
# kola run -p qemu -b rhcos --qemu-image tmp/rhcos-4.6.0-x86_64-qemu.qcow2 basic

set -euo pipefail

dn=$(dirname "$0")
# shellcheck source=src/cmdlib.sh
. "${dn}"/cmdlib.sh


print_help() {
    cat 1>&2 <<EOF
Usage: nestos-assembler offline-update --help
       nestos-assembler offline-update [--build ID] [--commit COMMIT] DISK

  In-place update DISK to the OSTree commit from the provided build.
EOF
}

rc=0
build=
commit=
options=$(getopt --options h --longoptions help,build,commit: -- "$@") || rc=$?
[ $rc -eq 0 ] || {
    print_help
    exit 1
}
eval set -- "$options"
while true; do
    case "$1" in
        -h | --help)
            print_help
            exit 0
            ;;
        --build)
            build=$2
            shift
            ;;
        --commit)
            commit=$2
            shift
            ;;
        --)
            shift
            break
            ;;
        -*)
            fatal "$0: unrecognized option: $1"
            ;;
        *)
            break
            ;;
    esac
    shift
done

if [ $# -gt 1 ]; then
    print_help
    fatal "Too many arguments passed"
fi
if [ $# -eq 0 ]; then
    print_help
    fatal "Missing required argument"
fi

disk=$(realpath "$1")
shift
workdir=$(pwd)
TMPDIR=${workdir}/tmp

if [ -z "${commit}" ]; then
if [ -z "${build}" ]; then
    build=$(get_latest_build)
    if [ -z "${build}" ]; then
        fatal "No build found."
    fi
fi

builddir=$(get_build_dir "$build")
if [ ! -d "${builddir}" ]; then
    fatal "Build dir ${builddir} does not exist."
fi

commit=$(json_key ostree-commit)
fi

runvm -drive if=virtio,id=target,format=qcow2,file="${disk}" -- \
    /usr/lib/coreos-assembler/offline-update-impl "${workdir}/tmp/repo" "${commit}" "1"
